package solution;

import java.util.Arrays;

class Solution {
    public static void main(String[] args) {
        int[] num = {1,3,5,6};
        int x = searchInsert(num, 5);
        System.out.println(x);
    }
    /**
     *35. 搜索插入位置
     * https://leetcode.cn/problems/search-insert-position/description/
     */
    public static int searchInsert(int[] nums, int target) {
        //二分查找
        int left = 0;
        int right = nums.length -1;
        int result = nums.length;
        while(left <= right) {
            int mid = ((right - left) >> 1) + left;
            if(nums[mid] >= target) {
                result = mid;
                right = mid - 1;
            }else {
                //nums[mid] < target
                left = mid + 1;
            }
        }
        return result;
    }
    /**
     * 26. 删除有序数组中的重复项
     * https://leetcode.cn/problems/remove-duplicates-from-sorted-array/description/
     */
    public int removeDuplicates(int[] nums) {
        int len = nums.length;
        if(len == 0) {
            return 0;
        }
        int slow = 1;
        int fast = 1;
        while(fast < len) {
            if(nums[fast] != nums[fast - 1]) {
                nums[slow] = nums[fast];
                slow++;
            }
            fast++;
        }
        return slow;
    }

    /**
     * 27. 移除元素
     * https://leetcode.cn/problems/remove-element/description/
     * @param
     */
    public int removeElement2(int[] nums, int val) {
        //双指针解法，定义left和right，保证0到left的区间一定是有效部分，right往后遍历，是有效部分就放进left里，不是就往后走
        int left = 0;
        for(int right = 0; right < nums.length; right++) {
            if(nums[right] != val) {
                nums[left] = nums[right];
                left++;
            }
        }
        return left;
    }

    public static int removeElement(int[] nums, int val) {
        int j = nums.length - 1;
        for (int i = 0; i <= j; i++) {
            if (nums[i] == val) {
                swap(nums, i--, j--);
            }
        }
        return j + 1;
    }
    static void swap(int[] nums, int i, int j) {
        int tmp = nums[i];
        nums[i] = nums[j];
        nums[j] = tmp;
    }
}